<!-- 首页 -->
<template>
	<view class="container">
		
		<view class="tabs">
			<view class="uni-tab-item-title" :class="current == 0 ? 'uni-tab-item-title-active':''" @click="handleChangeType(0)">任务号码</view>
            
            <view class="uni-tab-item-title" :class="current == 1 ? 'uni-tab-item-title-active':''" @click="handleChangeType(1)">公海</view>
            
			<view class="uni-tab-item-title" style="float:right;" >
				<u-button class="submitBtn" @click.stop="handleShowAddInfo()" :custom-style="btnStyle" type="primary" style="float:right;margin-right:13rpx;border-radius: 50rpx;height:60rpx;background: linear-gradient(90deg, #5498ff 0%, #34b1ff 100%);" ><uni-icons type="plusempty" color="#fff" size="22"></uni-icons></u-button>
                
                <!-- <u-button class="submitBtn" @click.stop="handleShowScanNumber()" :custom-style="btnStyle" type="primary" style="float:right;margin-right:23rpx;border-radius: 50rpx;height:60rpx;background: linear-gradient(90deg, #5498ff 0%, #34b1ff 100%);" ><uni-icons type="scan" color="#fff" size="22"></uni-icons></u-button> -->
                
                
			</view>
		</view>
		
		<view>
			<view class="call_search">
				<u-form :model="baseFormData" ref="uForm" :label-style="{fontSize:'30rpx'}">
					<u-form-item label="">
                        <view class="c_type">
                            <view style="width:96%;margin-left:2%;float:left;">

                                <u-input placeholder="输入号码查询" v-model="baseFormData.num" height="60" :border="true" style="background-color:#ffffff;font-size:32rpx;width:calc(100% - 90rpx);float:left;" :clearable="false" />
                                
                                <u-button @click.stop="handleSearchCallOut()" class="submitBtn"  :custom-style="btnStyle" type="primary" style="width:80rpx;float:right;" ><uni-icons type="search" color="#fff" size="22"></uni-icons></u-button>
                            </view>
                            
                            <view style="width:96%;margin-left:2%;float:left;">
                                <view style="width:100%;float:left;">
                                    <view @click="eventTaskShow = true" style="float:left;text-align: center;" :style="current == 0 ?'width:70%':'width:100%'">
                                        <text>{{baseFormData.taskName}}</text><uni-icons type="bottom" size="17"></uni-icons>
                                    </view>
                                    <u-select :list="taskData" value-name="id" label-name="name" v-model="eventTaskShow" @confirm="eventTaskCallback" style="z-index: 1000000000000000000000000000000000000000000000;position: fixed;bottom:0rpx;"></u-select>
                                    
                                    <view @click="eventStatusShow = true" style="width:30%;float:left;text-align:center;" v-show="current == 0">
                                        <text>{{baseFormData.statusName}}</text><uni-icons type="bottom" size="17"></uni-icons>
                                    </view>
                                     <u-select :list="statusRange" v-model="eventStatusShow" @confirm="eventStatusCallback"></u-select>
                                 </view>
                            </view>
                        </view>
					</u-form-item>
				</u-form>
			</view>
        
			
			<!-- 任务号码 -->
			<view class="call_log_list" ref="call_out_list" v-show="current == 0">
				<view :class="autoCallIndex == item.id ? 'call_log_item_current':(item.status == 4 ? 'call_log_item_del':'call_log_item')" :ref="'box_center_' + index" v-for="(item,index) in taskList" :data-id="item.id" :data-index="index" :key="index" :id="'scroll' + item.id" >
                    
                    <view class="call_log_type">
                    	<!-- 未呼通 -->
                    	<i class="iconfont" v-if="item.status == '3'" :style="item.status == '3' ? 'color:#ff0000;background-color:#e80f331c;':''" @click="toggleActions(index)">&#xe96a;</i>
                    	<!-- 呼通 -->
                    	<i class="iconfont" v-else :style="item.status != '3' ? 'color:green;background-color:#0fe82c1c;':''" @click="toggleActions(index)">&#xe967;</i>
                    </view>
						
						<view class="call_log_info">
							<text class="phone_number" :class="(item.status == 3 || item.status == 11) ? 'text_red':''" >{{item.num ? item.num : '' }}&nbsp;&nbsp;&nbsp;&nbsp;<font style="color:#34b1ff;margin-left:20px;">{{item.type == '0' ? '成交库':((item.type == '' || item.type == null) ? '':item.type)}}</font></text>
							<view class="phone_time">项目:<text>{{item.project_name}} &nbsp;&nbsp;<span v-if="item.task_name != ''" style="margin-left:20rpx;">任务:{{item.task_name}}</span></text></view>
						</view>

						<view class="call_log_detail" @click.stop="handleViewTask(item,index)">
							<text class="text">详情</text>

							<view v-if="item.status == '0'" class="call_log_time">待呼</view>
							<view v-if="item.status == '10'" class="call_log_time" style="color:#10ac28">初始</view>
							<view v-if="item.status == '3'" class="call_log_time" style="color:red">未呼通</view>
							<view v-if="item.status == '2'" class="call_log_time">呼通</view>
                            <view v-if="item.status == '1'" class="call_log_time">已呼</view>
							<view v-if="item.status == '5'" class="call_log_time" style="color:red">呼损</view>
                            <view v-if="item.status == '11'" class="call_log_time" style="color:red">黑名单</view>
						</view>
                        
                        <CallType :isShowCallType="item.showActions" :callData="item" @closeShowCallType="handleCloseShowCallType" @changeNumStatus="handleChangeNumStatus" callType="info" :callKey="index" />

				</view>
            </view>
			<!-- </view> -->
			
			<!-- 号码池 -->
			<view class="call_log_list" ref="call_out_list" v-show="current == 1">
				<view :class="autoCallIndex == item.id ? 'call_log_item_current':(item.status == 4 ? 'call_log_item_del':'call_log_item')" :ref="'box_center_' + index" v-for="(item,index) in custList" :data-id="item.id" :data-index="index" :key="index" :id="'scroll' + item.id" >
					
					<!-- <liu-swipe-action :index="index" :btnList="[]"> -->
                    
                    <view class="call_log_type">
                    	<!-- 未呼通 -->
                    	<i class="iconfont" v-if="item.status == '3'" :style="item.status == '3' ? 'color:#ff0000;background-color:#e80f331c;':''" @click="toggleActions(index)">&#xe96a;</i>
                    	<!-- 呼通 -->
                    	<i class="iconfont" v-else :style="item.status != '3' ? 'color:green;background-color:#0fe82c1c;':''" @click="toggleActions(index)">&#xe967;</i>
                    </view>
						
						<view class="call_log_info">
							<text class="phone_number" :class="(item.status == 3 || item.status == 11) ? 'text_red':''" >{{item.num ? item.num : '' }}</text>
							<view class="phone_time">项目:<text>{{item.project_name}} &nbsp;&nbsp;<span v-if="item.task_name != ''" style="margin-left:20rpx;">任务:{{item.task_name}}</span></text></view>
						</view>
			
						<view class="call_log_detail" @click.stop="handleViewTask(item,index)">
							<text class="text">详情</text>

							<view v-if="item.status == '0'" class="call_log_time">待呼</view>
							<view v-if="item.status == '1'" class="call_log_time" style="color:#10ac28">已呼</view>
							<view v-if="item.status == '3'" class="call_log_time" style="color:red">未呼通</view>
							<view v-if="item.status == '2'" class="call_log_time">呼通</view>
							<view v-if="item.status == '5'" class="call_log_time" style="color:red">呼损</view>
                            <view v-if="item.status == '11'" class="call_log_time" style="color:red">黑名单</view>
						</view>
                        
                        <CallType :isShowCallType="item.showActions" :callData="item" @closeShowCallType="handleCloseShowCallType" @changeNumStatus="handleChangeNumStatus" callType="info" :callKey="index" />
					<!-- </liu-swipe-action> -->
				</view>
			</view>
			
			<!-- <view style="width:100%;height:50rpx;float:left;clear:both;"></view> -->
		</view>
        
        <AddInfo :detailData="current_data" :isShowAddInfo="isShowAddInfo" @closeInfoPop="handleCloseInfoPop" :taskData="taskData" />
		
		<!-- 显示订单详情 -->
		<CallOrder :isShowDetail="isShowDetail" :currentData="taskForm" @changeNumType="handleChangeNumType" @changeNumStatus="handleChangeNumStatus" @closeCallOrder="closeCallOrder" popType='cust' :styleData="'height:70%;margin-top:-200rpx;'" />
        
        <!-- 添加号码 -->
        <ScanNumber :isShowScanNumber="isShowScanNumber" :scanData="scanData" @closeScanPop="closeScanPop" :styleData="'height:70%;margin-top:-100rpx;'" />
		

		<u-toast ref="uToastsInfo" />
		
		<u-modal v-model="isCalls" :show-cancel-button="true" :title-style="{fontSize:'40rpx'}" confirm-text="去开启" :show-title="false" title="未开启通话自动录音功能无法卡外呼" @cancel="isCalls = false" @confirm="confirmOpenVoice">
            <text style="font-size:38rpx;font-weight: bold;display: block;width:98%;padding-left:1%;line-height:45rpx;margin-top:20rpx;">未开启通话自动录音功能无法卡外呼</text>
		    <view class="slot-content" style="height:400rpx;">
		        <text>请自动开启通话录音功能,否则无法进行外呼并生成通话录音。以下为开启方法:</text>
		        <text>1.在手机自带拨号盘通话设置中,开启'通话自动录音'</text>
		        <text>2.在系统设置中,搜索'自动录音'或'通话设置',开启'通话自动录音'</text>
		    </view>
		</u-modal>
	</view>
       
    
</template>

<script>
	// 通话类型,1呼入,2呼出,3未呼通

	import {getTime} from "@/utils/data.js";
    
    import {isBlackByNumber,uploadImgToOCR} from "@/api/index.js";
	
	import AddInfo from "@/pages/index/addInfo.vue";
    
    import ScanNumber from "@/pages/index/scanNumber.vue";
	
	import {
		getSeatCallOutList,
		createCallOrder,
		saveCallOut,
		checkNumberTypePV,
		
		getTaskByProjectAndSeat,
		getSeatCallOutByNoSeat,
        getClickToDial,
        changeCallNumStatus
	} from "@/api/task.js";
	
	import {
		mapGetters,mapState
	} from "vuex";
	
	import CallOrder from "../components/callOrder.vue";
    import CallType from "../components/callType.vue";
	
	let that;
    let autoCallTimer = null; //自

	const callModule = uni.requireNativePlugin("leven-call-CallModule");

	export default {
		 name:"infoself",
		data() {
			return {
                xInfo:200,
                yInfo:200,
                
				duration: 1,
				
				tabIndex:1,
				popupVisible: false,

				taskList:[],
				custList:[],
				keyword:'',
				pageSize:10,//一次取多少条
				currentPage:1,//当前页数
				
				clientX: 0,
				
				currentDeleteIndex:0,
				
				baseFormData:{
					num:'',
					status:'',
                    tid:'',
                    taskName:'任务',
					statusName:'状态'
				},
                
                eventTaskShow:false,
				
				statusRange: [
					{
						value: '',
						label: "全部"
					},
					{
						value: 1,
						label: "未呼"
					},
					{
						value: 2,
						label: "接通"
					},
					{
						value: 3,
						label: "未呼通"
					},
					{
						value:5,
						label:'呼损'
					}
				],
                
                eventStatusShow:false,
				
                taskData:[],
                
				inputStyle:{
					fontSize:'30rpx',
					lineHeight:'50rpx',
					height:'50rpx'
				},
				
				btnStyle: {
					border: 'none',
					borderRadius: '20rpx',
					color: '#fff',
					height:'70rpx',
					padding:'20rpx 10rpx',
					margin:'0rpx'
				},
				
				btnFormStyle: {
					border: 'none',
					borderRadius: '10rpx',
					color: '#fff',
					height:'70rpx',
					padding:'20rpx 30rpx',
					margin:'0rpx',
					float:'right',
					marginLeft:'15rpx'
				},
				
				eventScaleShow: false,
				
				isShowDetail:false,
                isShowScanNumber:false,
                scanData:"",
				
				taskForm:{
					remark:'',
					phone_number:'',
					status:"",
					address:''
				},
				
				statusName:'',
				
				overlayStyle:{
					display:'none',
					marginBottom:'200rpx',
					bottom:'200rpx',
					position:'absolute'
				},
				
				taskFormLabel:{
					marginLeft:'20rpx',
					fontSize:'30rpx'
				},
				
				isSubmit:false, //是否点击提交按钮
				
				isShowAddInfo:false, //是否显示添加任务窗口
				current_data:[],
				
				isAutoCall:0, //是否开启自动外呼
				autoCallIndex:0, //自动外呼到第几个
                autoScrollId:'scroll0', //自动外呼的当前ID
				
				isFilter:0, //是否开启过滤功能，0关闭，1开启
				
				currentPhoneNumber:'',//当前通话号码 
				phonetype:'',
                
                typeList:[
                    {
						name: '任务'
					}, 
					{
						name: '公海'
					}
                ],
                current: 0, //标签当前类型，任务号码，公海
				isCalls:false
			};
		},
		computed: {
			...mapGetters(["userInfo","voiceServiceList","taskType","seatNumType","autoCallStatus","callStatus","callNextType","callingData","currentCallType","isSip","callStatus"]),
			...mapState({
				callType: state => state.task.callType,
                seatNumType:state => state.app.seatNumType,
                autoCallStatus:state => state.task.autoCallStatus,
                callNextType:state=>state.app.callNextType,
                callingData:state=>state.task.callingData,
                currentCallType:state=>state.task.currentCallType,
                isSip:state=>state.task.isSip
			})
		},
		created() {			
			uni.$on("appendInfoList",this.handleAppendInfoList);
			
			that = this;
            
            // const systemInfo = uni.getSystemInfoSync();
            // this.xInfo = systemInfo.screenWidth - 70;
            // this.yInfo = systemInfo.screenHeight - 120;
			
			//获取任务列表
			this.handleGetTaskBySeat();
            
		},
		components:{
			AddInfo,
			CallOrder,
            CallType,
            ScanNumber
		},
		methods: {
			//开启自动通话录音
			confirmOpenVoice() {
				callModule.toCallAutoRecorderPage(res => {
					console.log("开启通话自动录音",res);
					
					this.$console.info("开启通话自动录音",res);
				});
			},
                        
            //扫描文件，并识别内容中的号码
            handleShowScanNumber(){
                // this.isShowScan = true;
                console.log("handleshowscannumber");
                
                this.isShowScanNumber = true;
				
				// uni.chooseImage({
				// 	count: 1, // 最多可选择的图片数量，默认9
				// 	sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				// 	sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					
				// 	success: (res) => {
				// 		console.log('选择成功:', res);
						
				// 		uni.showLoading({ title: '处理中...', mask: true });
					  
				// 		// 自动上传图片
    //                     let baseApiUrl = uni.getStorageSync("baseApiUrl");
    //                     let uploadUrl = 'http://' + baseApiUrl + '/api/AppIndex/uploadImgToOCR';
                        
    //                     uni.uploadFile({
    //                         url: uploadUrl,
    //                         filePath: res.tempFilePaths[0],
    //                         name: 'file', // 后台接收的文件字段名
    //                         formData: {
    //                           // 附加参数示例
    //                           userId: this.userInfo.seat,
    //                         },
    //                         header: {
    //                           'Authorization': 'Bearer your-token' // 如果需要认证
    //                         },
    //                         success: (uploadRes) => {
    //                           console.log("uploadres",uploadRes);
							  
				// 			  uni.hideLoading();
                              
    //                           // 处理上传成功响应（根据后台返回格式调整）
    //                           const data = uploadRes;
    //                           if (data.statusCode === 200) {
    //                             this.isShowScanNumber = true;
    //                             this.scanData = JSON.parse(data.data);
    //                           } else {
    //                             this.$refs.uToastsInfo.show({
    //                             	title: `上传失败: ${data.errMsg}`,
    //                             	type: 'error',
    //                             	duration: '2000',
    //                             });
    //                           }
    //                         },
    //                         fail: (err) => {
    //                           console.error('上传失败:', err);
							  
				// 			  uni.hideLoading();
                              
    //                           this.$refs.uToastsInfo.show({
    //                           	title: '上传失败，请检查网络',
    //                           	type: 'error',
    //                           	duration: '2000',
    //                           });
    //                         }
    //                     });
                        
				// 	},
					
				// 	fail: (err) => {
				// 		console.error('选择图片失败:', err);
						
				// 		uni.hideLoading();
						
				// 		uni.showToast({
				// 			title: '选择图片失败',
				// 			icon: 'none'
				// 		});
				// 	}
				// });
            
			},
			
            //关闭扫描内容
            closeScanPop(type){
                this.isShowScanNumber = false;
				
				this.scanData = "";
                
                console.log("handleclose",type);
				
				if(type == '1'){
					// this.handleInitData();
				}
            },
            
            // 切换操作按钮的显示状态
            toggleActions(index) {
            	console.log("toggleactions ", index,this.current);
                if(this.callStatus == 0){
                    if(this.current == 0){
                        this.taskList.forEach((item, i) => {
                            item.showActions = i === index ? !item.showActions : false;
                        });
                        
                        console.log("taskList",this.taskList);
                    }else{
                        this.custList.forEach((item, i) => {
                            item.showActions = i === index ? !item.showActions : false;
                        });
                        
                        console.log("custlist",this.custList);
                    }
                
                    // 强制更新视图（解决动态对象属性更新问题）
                    this.$forceUpdate();
                }
            },
            
            //直接呼叫下一个未呼号码
            handleCallNext(){
                let current_data = {};
                let nums = 0; //未呼号码数，判断是否有可呼号码
                
                console.log("handlecallnext aaaaaaaaaaaaaa",that.current);
                
                if(that.isAutoCall == 0){
                    //判断是任务号码还是号码池
                    if(that.current == 1){
                        //号码池   
                        let cust_list = that.custList;
                        for(let i = 0;i<cust_list.length;i++){
                            if(cust_list[i].status == 0 || cust_list[i].status == 10){
                                current_data = cust_list[i];
                                nums++;
                                break;
                            }
                        }
                    }else if(that.current == 0){
                        //任务号码
                        let task_list = that.taskList;
                        for(let i = 0;i<task_list.length;i++){
                            if(task_list[i].status == 0 || task_list[i].status == 10){
                                current_data = task_list[i];
                                nums++;
                                break;
                            }
                        }
                    }
                    
                    if(nums == 0){
                        uni.showToast({
                            title: '已没有未呼号码！',
                            duration: 2000,
                            icon: "none"
                        });
                        
                        that.$globalData.autoCallStatus = 0;
                        that.isAutoCall = 0;
                        
                        that.autoCalllIndex = 0;
                        that.autoScrollId = "scroll0";
                    }else{
                        // that.autoCallIndex = current_data.id;
                        // that.autoScrollId = "scroll"+current_data.id;
                        
                        // that.$console.info("任务--自动外呼",current_data);
                        
                        that.handleCheckCallPhone(current_data);
                    }
                }
            },
            
            //自动呼叫下一个未呼号码
            handleAutoCallNext(){
                let current_data = {};
                let nums = 0; //未呼号码数，判断是否有可呼号码
                
                console.log("handleAutoCallNext aaaaaaaaaaaaaa");
                
                if(this.isAutoCall == 1){
                    //判断是任务号码还是号码池
                    if(this.current == 1){
                        //号码池   
                        let cust_list = this.custList;
                        for(let i = 0;i<cust_list.length;i++){
                            if(cust_list[i].status == 0 || cust_list[i].status == 10){
                                current_data = cust_list[i];
                                nums++;
                                break;
                            }
                        }
                    }else if(this.current == 0){
                        //任务号码
                        let task_list = this.taskList;
                        for(let i = 0;i<task_list.length;i++){
                            if(task_list[i].status == 0 || task_list[i].status == 10){
                                current_data = task_list[i];
                                nums++;
                                break;
                            }
                        }
                    }
                    
                    if(nums == 0){
                        uni.showToast({
                            title: '已没有未呼号码！',
                            duration: 2000,
                            icon: "none"
                        });
                        
                        this.$globalData.autoCallStatus = 0;
                        this.isAutoCall = 0;
                        
                        this.autoCalllIndex = 0;
                        this.autoScrollId = "scroll0";
                    }else{
                        
                        
                        this.handleCheckCallPhone(current_data);
                    }
                }
            },
            
            //统一检测呼叫号码  是否为黑名单
            handleCheckCallPhone(data){
                let _this = this;
                
                let call_next_type = uni.getStorageSync("callNextType");
                
                console.log("handlecallphone data:",data,call_next_type);
                
                if(call_next_type == "" || call_next_type == null || call_next_type == undefined){
                    call_next_type = 'call';
                    uni.setStorageSync("callNextType","call");
                }
                
                if(data.num == ""){
                	_this.$refs.uToastsInfo.show({
                		title: "号码为空无法呼叫！",
                		type: 'error',
                		duration: '2000',
                	});
                    
                    return false;
                }
                
                if(call_next_type == 'back'){
                    if(_this.userInfo.shownum == "" || _this.userInfo.shownum == '0'){
                        _this.$refs.uToastsInfo.show({
                        	title: "请设置外呼主叫号码",
                        	type: 'error',
                        	duration: '3000',
                        });
                        
                        return false;
                    }
                }
                
                if(call_next_type == 'sip'){
                    if(_this.isSip == 0 || _this.isSip == '0'){
                        _this.$refs.uToastsInfo.show({
                        	title: "请先注册SIP",
                        	type: 'error',
                        	duration: '3000',
                        });
                        
                        return false;
                    }
                    
                    if(_this.callStatus == 1){
                        _this.$refs.uToastsInfo.show({
                        	title: "通话中，稍后操作",
                        	type: 'error',
                        	duration: '3000',
                        });
                        
                        return false;
                    }
                }
                
                _this.autoCallIndex = data.id;
                _this.autoScrollId = "scroll"+data.id;
                
                console.info("任务--自动外呼",data);
                _this.$console.info("任务--自动外呼",data);
                
                //检测是否为黑名单
                isBlackByNumber({'cid':_this.userInfo.companyid,'num':data.num,'seat':this.userInfo.seat}).then(res=>{
                    console.log("infoself isblackbynumber res",res);
                    
                    // if(res.data.data.is_black == 1){
                    if(res.data.data.is_black >= 1){
                        let title_str = res.data.data.is_black == 1 ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':(res.data.data.is_black == 2 ? '已开启黑名单过滤，该号码为企业黑名单，禁止外呼！':'已开启黑名单过滤，该号码为系统黑名单，禁止外呼！');
                        _this.$refs.uToastsInfo.show({
                        	title: title_str,
                        	type: 'error',
                        	duration: '1000',
                        });
                        
                        _this.$store.dispatch("setCallStatus",0);
                        _this.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
                        
                        _this.$store.dispatch("setCurrentCallType","");
                        
                        //修改列表号码状态
                        _this.handleChangeNumStatus({'status':11,'num':data.num});
                    }else{
                        _this.$store.dispatch("setCurrentCallType",call_next_type);
                        
                        if(call_next_type == "back"){
                            //回拨
                            _this.handleCallBack(data);
                        }else if(call_next_type == 'call'){
                            //外呼
							
							if(res.data.data.is_call == 1){
								callModule.checkCallAutoRecorder(res_module => {
									console.log("检测通话录音权限 结果",res_module);
									
									_this.$console.info("检测通话录音权限 结果",res_module);
									
									if(!res_module.data.isOpen){
										console.log("未开启自动通话录音");
										
										_this.$console.info("未开启自动通话录音");
										
										//提示，没有开启自动通话录音
										_this.isCalls = true;
										
									}else{
										_this.isCalls = false;
										_this.handleCallPhone(data);
									}
								});
							}else{
								_this.handleCallPhone(data);
							}
                            // _this.handleCallPhone(data);
                        }else if(call_next_type == 'sip'){
                            //SIP
                            _this.handleCallSip(data);
                        }
                    }
                });
            },
            
            //回拨
            handleCallBack(data){
        
                //调用接口
                let params = {
                    'company_id':this.userInfo.companyid,
                    'caller':this.userInfo.seat,
                    'callee':data.num,
                    'seat':this.userInfo.seat,
                    'type':5,
                    'pid':this.userInfo.pid,
                    'shownum': this.userInfo.shownum,
                    'phone': data.num,
                    'cid': this.userInfo.companyid,
                    'id':data.id
                }
                  
                console.log("callorder params",params);
              
                console.info("任务外呼--参数",params);
                this.$console.info("任务外呼--参数",params);
                  
                console.info("任务外呼--先停止定时任务 ",params.callee);
                this.$console.info("任务外呼--先停止定时任务 ",params.callee);
                  
                // //先清除任务
                clearInterval(this.$globalData.taskTimer);
                this.$globalData.taskTimer = null;
                  
                //先调用回拨接口，有返回结果后保存通话记录
                getClickToDial(params).then(res => {
                    console.log("getClickToDial res", res);
                    this.$console.info("任务外呼--回拨接口成功 返回数据",res);
                      
                    if(res.data.code == 200){
                        this.$refs.uToastsInfo.show({
                            title: "回拨成功",
                            type: 'success',
                            duration: '2000',
                        });
                          
                        //通话状态监听
                        params.start_time = new Date().getTime();
                                                      
                        //放入全局参数
                        // this.$globalData.callData = params;
                          
                        //记录日志
                        console.info("任务外呼--开始外呼 ", params.callee);
                        this.$console.info("任务外呼--开始外呼 ",params.callee);
        
                    }else{
                        this.$refs.uToastsInfo.show({
                            title: res.data.msg,
                            type: 'error',
                            duration: '3000',
                        });
                          
                        console.info("任务外呼--回拨接口失败 返回数据 ", params.callee);
                        this.$console.info("任务外呼--回拨接口失败 返回数据 ", params.callee);
                          
                        //开启任务定时器
                        if(this.taskType == 0 && this.$globalData.taskTimer == null){
                            this.$globalData.taskTimer = setInterval(()=>{
                                uni.$emit("handleGetCall");
                            },2000);
                        }
                    }
                }).catch(err => {
                      console.info("任务外呼--回拨接口错误 返回数据 err", params.callee,err);
                      this.$console.info("任务外呼--回拨接口错误 返回数据 ", params.callee,err);
                      
                      //开启任务定时器
                      if(this.taskType == 0 && this.$globalData.taskTimer == null){
                          this.$globalData.taskTimer = setInterval(()=>{
                              uni.$emit("handleGetCall");
                          },2000);
                      }
                  });
        
              },
              
            //SIP
            handleCallSip(data){
                this.$console.info("快速外呼--SIP外呼 ", data);
                  
                //设置通话状态为通话中
                this.$store.dispatch("setCallStatus",1);
                        
                this.$store.dispatch("setCallingData",{id:data.id,phone:data.num,type:uni.getStorageSync("callNextType")});
                  
                // this.$store.dispatch("setPageCur","websip");
                  
                this.$store.dispatch("setSipPhone",data.num);
                this.$store.dispatch("setIsShowWebSip",1);
            },
                  
            
            //呼叫号码
            handleCallPhone(data){
                let _this = this;
                
                console.log("handlecallphone data:",data);
                
                //设置通话状态为通话中
                this.$store.dispatch("setCallStatus",1);
                
                this.$store.dispatch("setCallingData",{id:data.id,phone:data.num,type:uni.getStorageSync("callNextType")});
                
                //调用接口
                let params = {
                	'company_id':_this.userInfo.companyid,
                	'caller':_this.userInfo.seat,
                	'callee':data.num,
                	'seat':_this.userInfo.seat,
					'type':3,
                    'pid':(data.pid == "" || data.pid == null || data.pid == undefined) ? _this.userInfo.pid : data.pid,
                    'tid':data.tid,
                    'phone':data.num
                }
                    
                console.info("任务外呼--外呼参数 ",params);
                _this.$console.info("任务外呼--外呼参数 ",params);
                
                console.info("任务外呼--先停止定时任务 ",params.callee);
                _this.$console.info("任务外呼--先停止定时任务 ", params.callee);
                
                //先清除任务
                clearInterval(_this.$globalData.taskTimer);
                _this.$globalData.taskTimer = null;
                
                //获取录音目录
                plus.io.requestFileSystem(
                    plus.io.PRIVATE_DOC, // 私有文档目录（对应 _doc 路径）
                    (fs) => {
                      // 定义目录路径（示例：在 _doc 下创建 myFolder）
                      let dirPath = 'logs';
                            
                      // 检查并创建目录
                      fs.root.getDirectory(
                        dirPath,
                        { create: true }, // 自动创建目录
                        (entry) => {
                            console.log('任务外呼--创建文件夹成功:',entry.fullPath);
                            _this.$console.info('任务外呼--创建文件夹成功:',entry.fullPath);
                            uni.setStorageSync("record_files",entry.fullPath);
                }, function(e) {
                        console.log('任务外呼--创建文件夹失败:',e.message);
                        _this.$console.info('任务外呼--创建文件夹失败:',e.message);
                    });
                }, function(e) {
                    console.log('任务外呼--请求文件系统失败:',e.message);
                    _this.$console.info('任务外呼--请求文件系统失败:',e.message);
                });
                        

                //修改列表号码状态
                _this.handleChangeNumStatus(data);
                
                //提前修改号码状态                    
                changeCallNumStatus(params).then(res=>{
                    //通话开始时间
                    params.start_time = getTime();
                    
                    console.info("任务外呼--接口修改号码状态 成功", params.callee);
                    _this.$console.info("任务外呼--接口修改号码状态 成功",params.callee);
                    
                    //记录日志
                    console.info("任务外呼--开始外呼 ",params.callee);
                    _this.$console.info("任务外呼--开始外呼 ",params.callee);
                    
                    //放入全局参数
                    _this.$globalData.callData.push(params);
					
					console.info("任务外呼--开始外呼 自动拨号",params.callee,_this.$globalData.callData);
					_this.$console.info("任务外呼--开始外呼 自动拨号",params.callee,_this.$globalData.callData);
					
					//启动通话状态监听
					if(_this.$globalData.callStatusTimer == null){
						_this.$globalData.callStatusTimer = setInterval(()=>{
							uni.$emit("handleRegisterListener");
						},500);
					}
                
                    //自动拨号
                    plus.device.dial(params.callee,false);
                    
                    console.log('外呼，完成');
                    _this.$console.info("任务外呼--转到手机系统外呼 ",params);
                }).catch(err=>{
                    console.info("任务外呼--接口修改号码状态 失败 err"+params.callee,err);
                    _this.$console.info("任务外呼--接口修改号码状态 失败 err "+params.callee,err);
                    
                    //设置通话状态为通话中
                    this.$store.dispatch("setCallStatus",0);
                    
                    this.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
                    
                    //开启任务定时器
                    if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
                        _this.$globalData.taskTimer = setInterval(()=>{
                            uni.$emit("handleGetCall");
                        },2000);
                    }
                });

            },
            
            //关闭号码列表 的快速拨号条
            //关闭所有的快速外呼条
            handleCloseShowCallType(){
                console.log("handleCloseShowCallType ");
                if(that.current == 0){
                    that.taskList.forEach((item, i) => {
                        item.showActions = false;
                    });
                }else{
                    that.custList.forEach((item, i) => {
                        item.showActions = false;
                    });
                }
                // 强制更新视图（解决动态对象属性更新问题）
                that.$forceUpdate();
            },
            
            //修改任务中号码的客户类型
            handleChangeNumType(data){
                //任务号码列表
                let task_list = that.taskList;
                
                console.log("handleChangeNumType data",data);
                
                task_list.map((item)=>{
                	if(item.num == data.phone){
                		item.type = data.type;
                	}
                	
                	return item;
                })
                
                that.taskList = task_list;
                console.log("修改任务号码类型后的数据 taskList",that.taskList);
            },
            
			//修改号码池状态
			handleChangeNumStatus(data){
                //号码池
				let cust_list = that.custList;
                
                let status = (data.status == undefined || data.status == "" || data.status == null) ? 1 : data.status;
				
				console.log("handleChangeNumStatus data",data);
				
				cust_list.map((item)=>{
					if(item.num == data.num){
						item.status = status;
					}
					
					return item;
				})
				
				that.custList = cust_list;
                console.log("修改号码池状态后的数据 custList",that.custList);
                
                //任务号码列表
                let task_list = that.taskList;
                
                console.log("handleChangeTaskNumStatus data",data);
                
                task_list.map((item)=>{
                	if(item.num == data.num){
                		item.status = status;
                	}
                	
                	return item;
                })
                
                that.taskList = task_list;
                console.log("修改号码池状态后的数据 taskList",that.taskList);
			},
			
            //任务选择返回处理数据方法
            eventTaskCallback(e){
                let current_label = e[0].label;
                let new_label = "";
                
                if(this.current == 0){
                    if(current_label.length > 15){
                        new_label = current_label.substring(0,8) + "...." + current_label.substring(current_label.length - 8);
                    }else{
                        new_label = current_label;
                    }
                }else{
                    if(current_label.length > 20){
                        new_label = current_label.substring(0,10) + "...." + current_label.substring(current_label.length - 10);
                    }else{
                        new_label = current_label;
                    }
                }
                
                this.baseFormData.taskName = new_label;
                this.baseFormData.tid = e[0].value;
            },
            
            //任务状态选择返回处理数据方法
            eventStatusCallback(e){
                this.baseFormData.statusName = e[0].label;
                this.baseFormData.status = e[0].value;
            },
            
			//获取任务列表
			handleGetTaskBySeat(){
                //先清空
                this.taskData = [];
                
                this.taskData.push({'id':'','name':'全部'});
                
				getTaskByProjectAndSeat({'seat':uni.getStorageSync("userInfo").seat}).then(res=>{
					console.log("getTaskByProjectAndSeat res",res);
					this.taskData = res.data.data;
                    
                    this.taskData.unshift({'id':'','name':'全部'});
				});
			},
			
			//子组件调用关闭窗口
			handleCloseInfoPop(type){
				this.isShowAddInfo = false;
				
				console.log("handlecloseinfopop type",type);
				
				if(type == '1'){
					this.handleInitData(1);
				}
			},
			
			//是否显示添加任务窗口
			handleShowAddInfo(){
				this.isShowAddInfo = true;
				
				console.log("handleshowaddinfo 11111111111");
			},
			
			//追加数据到顶部
			handleAppendInfoList(a){
				console.log("aaaaaaaaaaaaaaaaaaaaaaaaaa",a,that.taskList);
				
				a.assignment_time = getTime();
				a.status = 0;
				a.sec = 0;
			
				let new_task_list = [a];
				
				new_task_list = new_task_list.concat(that.taskList);
				
				console.log("new_task_list",new_task_list);
				
				that.taskList = new_task_list;
			},
			
			//加载数据，上拉刷新
			handleLoadMore(type){
				console.log("loadmore dddddddddd",this.currentPage,type);
				
				let that = this;
				setTimeout(() => {
                    if(type == 'start'){
                        if(that.current == 0){
                            that.currentPage = 1;
                            that.taskList = [];
                        }else{
                            that.custList = [];
                        }
                    }
                    
                    console.log("currentpage",that.currentPage);
				    that.handleInitData(1);
					
				}, 500)
			},
			
			//获取记录
			handleInitData(type){
                
                // if(type == 0){
                //     this.currentPage = 1;
                // }
                
                console.log("infoself hanldeinitdata",this.userInfo.id,this.userInfo.companyid,this.pageSize,this.currentPage);
                let params = {
                    seat:this.userInfo.seat,
                    limit:this.pageSize,
                    page:this.currentPage,
                    num:this.baseFormData.num,
                    status:this.baseFormData.status,
                    //is_filter:this.isFilter
                    type:this.current,
                    tid:this.baseFormData.tid,
                    cid:uni.getStorageSync("userInfo").companyid
                }
                
                console.log("handleInitData parasm",params,this.taskList,type);
                
                if((type == 0 && this.taskList.length == 0) || type == 1){
                    
                    if(this.current == 0){
                        uni.$emit('getLoadMoreState',"loading");
                        
                        //接口
                        getSeatCallOutList(params).then(res=>{
                            console.log("getSeatCallOutList res",res);
                            
                            if(res.data.code == 0){
                                
                                if(this.currentPage == 0){
                                    this.taskList = res.data.data;
                                }else{
                                    this.taskList = this.taskList.concat(res.data.data);
                                }
                                
                                if(res.data.data.length > 0){
                                    
                                    if(type == 0 && res.data.data.length < 10){
                                        uni.$emit('getLoadMoreState',"nomore");
                                    }else{
                                        
                                        this.currentPage++
                                        uni.$emit('getLoadMoreState',"more");
                                    }
                                }else{
                                    uni.$emit('getLoadMoreState',"nomore");
                                }
                            }else{
                                uni.$emit('getLoadMoreState',"nomore");
                            }
                            
                            uni.stopPullDownRefresh();
                        }).catch(err=>{
                            console.log("getSeatCallOutList err",err);
                            uni.$emit('getLoadMoreState',"nomore");
                            
                            uni.stopPullDownRefresh();
                        });
                    }else{
                        getSeatCallOutByNoSeat(params).then(res=>{
                            console.log("getSeatCallOutByNoSeat res",res);
                            
                            if(res.data.code == 0){
                                
                                this.custList = res.data.data;
                                
                            }
                            
                            uni.stopPullDownRefresh();
                        }).catch(err=>{
                            console.log("getSeatCallOutByNoSeat err",err);
                            
                            uni.stopPullDownRefresh();
                        });
                    }
                }
			},
			
			//列表点击事件，显示详情
			handleViewTask(data,i){
                console.log("handleViewTask isShowDetail",data,i);
				this.taskForm = data;
				// this.taskForm.type = this.current;
				
				this.isShowDetail = true;
			},
			
            //关闭订单详情窗口
			closeCallOrder() {
				this.isShowDetail = false;
				
				this.taskForm = {};
			},
			
			//搜索
			handleSearchCallOut() {
				this.currentPage = 0;
				
				console.log("handlesearchcallout ");
				
                if(this.isAutoCall == 0){
                    this.handleInitData(1);
                }
			},
            
            //切换类型
            handleChangeType(k){
                console.log("handleChangeType",k);
                
                //如果是自动外呼，不允许切换标签
                if(this.isAutoCall == 0){
                    this.current = k;
                    
                    this.$store.dispatch("setSeatNumType",k);
                    
                    //重新获取任务列表
                    this.handleGetTaskBySeat();
                
                    if(k == '1'){
                        this.baseFormData.tid = "";
                        this.baseFormData.taskName = "任务";
                        this.baseFormData.status = "";
                        this.baseFormData.statusName = "状态";
                        this.baseFormData.num = "";
                        
                        // 重新加载数据
                        this.handleInitData(1);
                    }
                }
            }
		},

		onLoad() {
			// this.openSQL();
			console.log("infoself onload");
		},
		onShow() {
			console.log("infoself onShow");
			// this.openSQL();
		},
		onLaunch() {
			console.log("infoself onLaunch");
		}
	};
</script>
<style lang="scss" scoped>
	
	page {
	    width: 100%;
	   
		
		background-color: #fff;
	}
	
	.label_text{
		font-size:30rpx;
		width:120rpx;
		padding-right:10rpx;
		padding-left:10rpx;
	}
	
	.submitBtn {
		background: linear-gradient(90deg, #0066ff 0%, #1371ff 100%);
	}
	
	.pop_title{
		font-size:32rpx;
		width:100%;
		padding-left:2%;
		padding-right:2%;
		height:100rpx;
		font-weight: bold;
		line-height: 100rpx;
		border-bottom:#ccc 1px solid;
	}
	
	.detail_pop{
		width:90%;
		margin-left:5%;
		border:#ccc 1px solid;
		background-color:'#f7f7f7';
		box-shadow:10rpx 10rpx 30rpx #ccc;
		border-radius:20rpx;
		position:fixed;
		// top:300rpx;
		// bottom:300rpx;
		top:20%;
		margin-bottom:30%;
		z-index:100000;
		overflow:hidden;
	}
	
	.container{
		width: 100%;
		color: #333333;
		background-image: linear-gradient(to bottom, #075AFF, #ffffff);
		background-size: 100% 45%;
		background-repeat: no-repeat;
		background-position: top center;
		overflow:hidden;
		height:auto;
		margin-bottom:100rpx;
		background-color: #fff;
	}
	
	.call_search{
		width:100%;
		height:150rpx;

		background-color: #eeeeef;
		
		border-bottom:#ececec 1px solid;
		
		position:fixed;
		top:150rpx;
		z-index:1000
	}
	
	.call_search_input{
		height:50rpx;
	}
	
	.call_log_list{
		width:100%;
		// height:auto;
		margin-top:300rpx;

		// overflow-y:auto;
		// height:calc(100vh - 420rpx);
        height:auto;
		float:left;
		clear:both;
		// position: absolute;
		margin-bottom:10rpx;
		background-color: #fff;
	}
	
	.call_log_item{
		width:100%;
		height:161rpx;
		float:left;
		border-bottom:#ececec 1px solid;
		background-color: #ffffff !important;
	
	}
	
	.call_log_item_del{
		width:100%;
		height:161rpx;
		float:left;
		border-bottom:#ececec 1px solid;
		background: #fff6f6 !important;
		
		animation: mymove 1s 1;
	}
    
    .call_log_item_current{
    	width:100%;
    	height:160rpx;
    	float:left;
        margin-top:1px;
    	border-bottom:#ec6c39 1px solid;
        border-top:#ec6c39 1px solid;
    	background: #fff2ee !important;
    }
	
	@keyframes mymove {
		0% {
			opacity: 1;
		}
		50% {
			opacity: 0.5;
		}
		100% {
			opacity: 0;
		}
	}
	
	.call_log_type{
		width:100rpx;
		height:158rpx;
		float:left;
	}
	
	.call_log_type .iconfont{
		font-size:35rpx;
		display: block;
		width:60rpx;
		height:60rpx;
		margin-left:20%;
		margin-top:45rpx;
		text-align: center;
		line-height: 60rpx;
		border-radius: 30rpx;
	}
	
	.call_log_info{
		width:calc(100% - 280rpx);
		float:left;
		height:60rpx;
		margin-top:20rpx;
		margin-left:0rpx;
	}
	
	.call_log_detail{
		width:220rpx;
		float:right;
		line-height:60rpx;
		height:60rpx;
	}
	
	.call_log_detail .text{
		line-height: 40rpx;
		color: #0e81a1;
		font-weight: bold;
		border: #ddf5ff 1px solid;
		padding:15rpx 20rpx;
		background-color: #e7f8ff;
		border-radius: 15rpx;
        
        display:block;
        width:100rpx;
        
        position: absolute;
        right:30rpx;
        margin-top:-30rpx;
        
        float:right;
	}
    
    .call_log_detail view{
    	line-height:40rpx;
    	font-weight:bold;
    	width:100rpx;
    	float:right;
    	position: absolute;
    	right:30rpx;
    	
    	text-align: right;
    	
    	margin-top:-20rpx;
    	// background-color: #0066ff;
    }
	
	.call_log_time{
		width:auto;
		margin-right:130rpx;
		font-size:25rpx;
		color:#3a3a3a;
		float:right;
		line-height:60rpx;
		height:60rpx;
		font-weight: bold;
	}
	
	.phone_number{
		width:100%;
		font-size:32rpx;
		font-weight: 500;
		line-height: 70rpx;
	}
	
	.text_red{
		color:#ff0000;
	}
	
	.phone_time{
		color:#909090;
	}
	
	.tabs {
	    background-color: #ffffff;
	    
		width:100%;
		height:190rpx;
		top:0rpx;
		// margin-left:20rpx;
	    
		position: fixed;
		z-index: 1000;
		
	}
	
	.uni-tab-item-title {
	    color: #555;
	    font-size: 36rpx;
	    line-height: 60rpx;
	    flex-wrap: nowrap;
		margin-left:20rpx;
        margin-right:20rpx;
		margin-top:80rpx;
		
		float:left;
	    /* #ifndef APP-PLUS */
	    white-space: nowrap;
	    /* #endif */
	}
	
	.uni-tab-item-title-active {
		font-size:36rpx;
		font-weight: bold;
		border-bottom:3px #0b2eb0 solid;
	}
    
    .c_type {
        width:98%;
        background-color: #eeeeef;
        height:70rpx;
        border-radius: 10rpx;
        margin-left:1%;
    }
    
    .call_next{
    	background-color:#075AFF;
    	border-radius: 60rpx;
    	color:#fff;
    	
    	width:120rpx;
    	height:120rpx;
    	
    	padding-top:25rpx;

    	text-align: center;
        line-height:35rpx;
    	
    	text-shadow: 5rpx 5rpx 5rpx #7a7a7a ;
    	box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
    }
    
    .call_next_nobtn{
    	background-color:#bfbfbf;
    	border-radius: 60rpx;
    	color:#fff;
    	
    	width:120rpx;
    	height:120rpx;
    	
    	padding-top:25rpx;
    	
    	text-align: center;
        line-height:35rpx;
    	
    	text-shadow: 5rpx 5rpx 5rpx #7a7a7a ;
    	box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
        
        pointer-events: none;
    }
	
</style>